import React, {useState, useEffect} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  TextInput,
  Alert,
  FlatList,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DatePicker from 'react-native-date-picker';
import Modal from 'react-native-modal';

const WeightTracker = () => {
  const [weightData, setWeightData] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [formData, setFormData] = useState({
    date: new Date(),
    weight: '',
    note: '',
  });

  // 从AsyncStorage加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        const data = await AsyncStorage.getItem('weightData');
        if (data) {
          setWeightData(JSON.parse(data));
        }
      } catch (error) {
        console.error('加载体重数据失败:', error);
      }
    };

    loadData();
  }, []);

  // 保存数据到AsyncStorage
  const saveData = async newData => {
    try {
      await AsyncStorage.setItem('weightData', JSON.stringify(newData));
    } catch (error) {
      console.error('保存体重数据失败:', error);
    }
  };

  // 提交表单
  const handleSubmit = () => {
    if (!formData.weight) {
      Alert.alert('错误', '请输入体重');
      return;
    }

    const newEntry = {
      id: editingId || Date.now(),
      date: formData.date.toISOString().split('T')[0],
      weight: parseFloat(formData.weight),
      note: formData.note,
    };

    let newData;
    if (editingId) {
      newData = weightData.map(item =>
        item.id === editingId ? newEntry : item,
      );
      setEditingId(null);
    } else {
      newData = [...weightData, newEntry].sort(
        (a, b) => new Date(a.date) - new Date(b.date),
      );
    }

    setWeightData(newData);
    saveData(newData);

    setFormData({
      date: new Date(),
      weight: '',
      note: '',
    });
    setShowForm(false);
  };

  // 编辑记录
  const handleEdit = item => {
    setFormData({
      date: new Date(item.date),
      weight: item.weight.toString(),
      note: item.note,
    });
    setEditingId(item.id);
    setShowForm(true);
  };

  // 删除记录
  const handleDelete = id => {
    Alert.alert('确认删除', '确定要删除这条记录吗？', [
      {text: '取消', style: 'cancel'},
      {
        text: '删除',
        style: 'destructive',
        onPress: () => {
          const newData = weightData.filter(item => item.id !== id);
          setWeightData(newData);
          saveData(newData);
        },
      },
    ]);
  };

  // 取消编辑
  const handleCancel = () => {
    setFormData({
      date: new Date(),
      weight: '',
      note: '',
    });
    setEditingId(null);
    setShowForm(false);
  };

  // 格式化日期
  const formatDate = dateString => {
    const date = new Date(dateString);
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
  };

  // 计算体重变化
  const getWeightChange = (currentWeight, index) => {
    if (index === 0) return null;
    const previousWeight = weightData[index - 1].weight;
    const change = currentWeight - previousWeight;
    return change;
  };

  // 渲染体重记录项
  const renderWeightItem = ({item, index}) => {
    const weightChange = getWeightChange(item.weight, index);

    return (
      <View style={styles.entryCard}>
        <View style={styles.entryHeader}>
          <Text style={styles.entryDate}>{formatDate(item.date)}</Text>
          <View style={styles.entryActions}>
            <TouchableOpacity
              style={styles.editBtn}
              onPress={() => handleEdit(item)}>
              <Icon name="edit" size={20} color="#667eea" />
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.deleteBtn}
              onPress={() => handleDelete(item.id)}>
              <Icon name="delete" size={20} color="#e74c3c" />
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.entryContent}>
          <View style={styles.weightInfo}>
            <Text style={styles.weightValue}>{item.weight.toFixed(1)} kg</Text>
            {weightChange !== null && (
              <Text
                style={[
                  styles.weightChange,
                  weightChange > 0 ? styles.weightIncrease : styles.weightDecrease,
                ]}>
                {weightChange > 0 ? '+' : ''}
                {weightChange.toFixed(1)} kg
              </Text>
            )}
          </View>
          {item.note && <Text style={styles.entryNote}>{item.note}</Text>}
        </View>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      {/* 添加按钮 */}
      <TouchableOpacity style={styles.addBtn} onPress={() => setShowForm(true)}>
        <Icon name="add" size={24} color="#fff" />
        <Text style={styles.addBtnText}>添加体重记录</Text>
      </TouchableOpacity>

      {/* 体重记录列表 */}
      <FlatList
        data={[...weightData].reverse()}
        renderItem={renderWeightItem}
        keyExtractor={item => item.id.toString()}
        showsVerticalScrollIndicator={false}
        contentContainerStyle={styles.listContainer}
        ListEmptyComponent={
          <View style={styles.emptyContainer}>
            <Icon name="monitor-weight" size={60} color="#ccc" />
            <Text style={styles.emptyText}>还没有体重记录</Text>
            <Text style={styles.emptySubText}>点击上方按钮添加第一条记录</Text>
          </View>
        }
      />

      {/* 添加/编辑表单模态框 */}
      <Modal
        isVisible={showForm}
        onBackdropPress={handleCancel}
        style={styles.modal}>
        <View style={styles.formContainer}>
          <Text style={styles.formTitle}>
            {editingId ? '编辑体重记录' : '添加体重记录'}
          </Text>

          {/* 日期选择 */}
          <TouchableOpacity
            style={styles.dateButton}
            onPress={() => setShowDatePicker(true)}>
            <Icon name="calendar-today" size={20} color="#667eea" />
            <Text style={styles.dateButtonText}>
              {formData.date.toLocaleDateString('zh-CN')}
            </Text>
          </TouchableOpacity>

          {/* 体重输入 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>体重 (kg)</Text>
            <TextInput
              style={styles.input}
              value={formData.weight}
              onChangeText={text => setFormData({...formData, weight: text})}
              placeholder="请输入体重"
              keyboardType="numeric"
            />
          </View>

          {/* 备注输入 */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>备注</Text>
            <TextInput
              style={[styles.input, styles.noteInput]}
              value={formData.note}
              onChangeText={text => setFormData({...formData, note: text})}
              placeholder="添加备注（可选）"
              multiline
              numberOfLines={3}
            />
          </View>

          {/* 按钮组 */}
          <View style={styles.buttonGroup}>
            <TouchableOpacity style={styles.cancelBtn} onPress={handleCancel}>
              <Text style={styles.cancelBtnText}>取消</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.submitBtn} onPress={handleSubmit}>
              <Text style={styles.submitBtnText}>
                {editingId ? '更新' : '添加'}
              </Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {/* 日期选择器 */}
      <DatePicker
        modal
        open={showDatePicker}
        date={formData.date}
        mode="date"
        onConfirm={date => {
          setShowDatePicker(false);
          setFormData({...formData, date});
        }}
        onCancel={() => {
          setShowDatePicker(false);
        }}
        title="选择日期"
        confirmText="确认"
        cancelText="取消"
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
    padding: 15,
  },
  addBtn: {
    backgroundColor: '#667eea',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    padding: 15,
    borderRadius: 12,
    marginBottom: 15,
  },
  addBtnText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 8,
  },
  listContainer: {
    paddingBottom: 20,
  },
  entryCard: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 15,
    marginBottom: 10,
    shadowColor: '#000',
    shadowOffset: {width: 0, height: 2},
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  entryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  entryDate: {
    fontSize: 14,
    color: '#666',
  },
  entryActions: {
    flexDirection: 'row',
    gap: 10,
  },
  editBtn: {
    padding: 5,
  },
  deleteBtn: {
    padding: 5,
  },
  entryContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  weightInfo: {
    flex: 1,
  },
  weightValue: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333',
  },
  weightChange: {
    fontSize: 14,
    marginTop: 4,
  },
  weightIncrease: {
    color: '#e74c3c',
  },
  weightDecrease: {
    color: '#27ae60',
  },
  entryNote: {
    fontSize: 14,
    color: '#666',
    fontStyle: 'italic',
    marginTop: 5,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 60,
  },
  emptyText: {
    fontSize: 18,
    color: '#999',
    marginTop: 15,
  },
  emptySubText: {
    fontSize: 14,
    color: '#ccc',
    marginTop: 5,
  },
  modal: {
    justifyContent: 'flex-end',
    margin: 0,
  },
  formContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: 20,
    maxHeight: '80%',
  },
  formTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 20,
    color: '#333',
  },
  dateButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
    marginBottom: 15,
  },
  dateButtonText: {
    marginLeft: 10,
    fontSize: 16,
    color: '#333',
  },
  inputGroup: {
    marginBottom: 15,
  },
  inputLabel: {
    fontSize: 14,
    fontWeight: 'bold',
    marginBottom: 5,
    color: '#333',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    backgroundColor: '#fff',
  },
  noteInput: {
    height: 80,
    textAlignVertical: 'top',
  },
  buttonGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 20,
  },
  cancelBtn: {
    flex: 1,
    backgroundColor: '#f8f9fa',
    padding: 15,
    borderRadius: 8,
    marginRight: 10,
  },
  cancelBtnText: {
    textAlign: 'center',
    fontSize: 16,
    color: '#666',
  },
  submitBtn: {
    flex: 1,
    backgroundColor: '#667eea',
    padding: 15,
    borderRadius: 8,
    marginLeft: 10,
  },
  submitBtnText: {
    textAlign: 'center',
    fontSize: 16,
    color: '#fff',
    fontWeight: 'bold',
  },
});

export default WeightTracker;
